package com.sky.aspect;

import com.sky.anno.TableInject;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 自动填充的切面类
 */
@Aspect
@Component
public class TableInjectAspect {
    //切点
    // 1.mapper下的方法
    // 2.必须加 @TableInject 注解
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.TableInject)")
    public void pt() {
    }

    // 我们需求是在sql执行之前把数据填充上
    @Before("pt()")
    public void before(JoinPoint jp) {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        //获取到当前正在执行的方法对象
        Method method = signature.getMethod();
        //通过method对象去获取注解对象
        TableInject tableInject = method.getAnnotation(TableInject.class);
        //获取方法接收的参数
        // employee category dish setmeal
        Object target = jp.getArgs()[0];
        //健壮性判断
        if (target==null || jp.getArgs().length == 0 || jp.getArgs().length>1){
            return;
        }
        //准备填充数据
        //执行目标方法的当前时间
        LocalDateTime now = LocalDateTime.now();
        //当前登陆的用户的id
        Long currentId = BaseContext.getCurrentId();

        try {
            //通过反射获取对应的set方法
            Method createTimeMethod = target.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method updateTimeMethod = target.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method createUserMethod = target.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method updateUserMethod = target.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            //获取注解对象选择的操作类型
            OperationType operationType = tableInject.value();
            switch (operationType) {
                case INSERT:
                    createTimeMethod.invoke(target,now);
                    updateTimeMethod.invoke(target,now);
                    createUserMethod.invoke(target,currentId);
                    updateUserMethod.invoke(target,currentId);
                    break;
                case UPDATE:
                    updateTimeMethod.invoke(target,now);
                    updateUserMethod.invoke(target,currentId);
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
